package com.jrx.anytxn.transaction.timer.job.queryLoanStatus.config;

import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.service.system.ICodeTableService;
import com.jrx.anytxn.ribbon.config.GrayVersionConfig;
import com.jrx.anytxn.transaction.bean.LoanSaveBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlDisbursementLog;
import com.jrx.anytxn.transaction.timer.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.timer.job.queryLoanStatus.step.QueryLoanStatusProcessor;
import com.jrx.anytxn.transaction.timer.job.queryLoanStatus.step.QueryLoanStatusWriter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 放款查询任务
 *
 * @author jing.xy
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class QueryLoanStatusConfiguration {

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;


    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;

    @Autowired
    DataSource dataSource;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    public GrayVersionConfig grayVersionConfig;

    @Autowired
    private ICodeTableService codeTableService;

    @Bean
    public Job queryLoanStatusJob() {
        return jobBuilderFactory.get("queryLoanStatusJob")
                .start(queryLoanStatusStep())
                .build();
    }

    @Bean
    public Step queryLoanStatusStep() {
        return stepBuilderFactory.get("queryLoanStatusStep")
                .<TlDisbursementLog,LoanSaveBean>chunk(anytxnBatchProperties.getQueryLoanStatusConfig().getChunkLimit())//表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(queryLoanStatusReader())
                .processor(queryLoanStatusProcessor())
                .writer(queryLoanStatusWriter())
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getQueryLoanStatusConfig().getThrottleLimit())//多线程
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<TlDisbursementLog> queryLoanStatusReader() {
        MyBatisCursorItemReader<TlDisbursementLog> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.transaction.mapper.ext.ExtTlDisbursementLogMapper.selectBySumStatus");

        Map<String, Object> map = new HashMap<>();
        map.put("sumStatus", TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_O);
        map.put("grayVersion", grayVersionConfig.getCurrentVersion());
        // 设置默认查询最大次数为0
        Integer queryMaxCounts = Integer.valueOf(0);
        // 查询放款结果查询最大次数系统配置
        List<PrCodeTable> prCodeTables = codeTableService.findListByCodeIds(TransBizConstant.DISBURSEMENT_QUERY_STATUS_COUNT,
                TransBizConstant.DEFAULT_TENANT_ID);
        if(CollectionUtils.isNotEmpty(prCodeTables)){
            // 获取v放款结果查询最大次数
            queryMaxCounts = Integer.valueOf(prCodeTables.get(0).getCodeId());
        }
        map.put("queryMaxCounts", queryMaxCounts);
        cursorItemReader.setParameterValues(map);
        //同步reader   线程安全
        SynchronizedItemStreamReader<TlDisbursementLog> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }

    @Bean
    @StepScope
    public QueryLoanStatusProcessor queryLoanStatusProcessor() {
        QueryLoanStatusProcessor queryLoanStatusProcessor = new QueryLoanStatusProcessor();
        return queryLoanStatusProcessor;
    }


    @Bean
    @StepScope
    public ItemWriter<LoanSaveBean> queryLoanStatusWriter() {
        return new QueryLoanStatusWriter();
    }

}
